﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace purchase.Oversell
{
    public class OversellSuccessLock
    {
        private static bool IsGoOn = true;
        private static object lockObj = new object();
        private static int index = 10;
        public static void Test()
        {

            for (int i = 0; i < 5000; i++)
            {
                int k = i;
                Task.Run(() =>//每个线程就是一个用户请求
                {
                    if (IsGoOn)
                    {
                        lock (lockObj)
                        {
                            index--;
                            //System.Threading.Thread.Sleep(300);
                            if (index >= 0)
                            {
                                Console.WriteLine($"{k.ToString("000")}秒杀成功，秒杀商品索引为{index}");
                                //service.Incr("Stock");//+1
                                //可以分队列，去数据库操作
                            }
                            else
                            {
                                if (IsGoOn)
                                {
                                    IsGoOn = false;
                                }
                                //Console.WriteLine($"{k.ToString("000")}秒杀失败，秒杀商品索引为{index}");
                            }
                        }
                    }
                    else
                    {
                        //Console.WriteLine($"{k.ToString("000")}秒杀停止......");
                    }
                });
            }
            Console.ReadKey();
        }
    }
}